package cn.tom.controller;

import cn.tom.entity.Usr;
import cn.tom.service.LargeFileService;
import cn.tom.service.UserService;
import cn.tom.tool.XJson;
import cn.tom.tool.XResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping({"/api/user"})
@RestController
public class UserInfoController {
    Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    UserService userService;
    @Autowired
    LargeFileService largeFileService;
    @Autowired
    PasswordEncoder passwordEncoder;

    @GetMapping({"/info"})
    public XJson getUserInfo() {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null) {
            return XResp.pack(401, "没有登录或登录超时", "");
        }
        Usr xu = this.userService.findByAccount(((UserDetails) who).getUsername());
        if (xu == null) {
            return XResp.pack(401, "该用户不存在", "");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("account", xu.getAccount());
        map.put("name", xu.getNickname());
        map.put("role", xu.getRole());
        map.put("img", xu.getImg());
        this.log.info(map.toString());
        return XResp.pack(200, "用户信息", map);
    }

    @GetMapping({"/shipInfo"})
    public XJson getUserShipInfo() {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null) {
            return XResp.pack(401, "没有登录或登录超时", "");
        }
        Usr xu = this.userService.findByAccount(((UserDetails) who).getUsername());
        if (xu == null) {
            return XResp.pack(401, "该用户不存在", "");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("name", xu.getNickname());
        map.put("phone", xu.getPhone());
        map.put("addr", xu.getAddr());
        this.log.info(map.toString());
        return XResp.pack(200, "用户发货信息", map);
    }

    @GetMapping({"/resetPwd/{uid}"})
    public XJson resetPwd(@PathVariable("uid") int uid) {
        this.userService.updatePwd(uid, "123456");
        return XResp.pack(200, "密码重置成功", "");
    }

    @PostMapping({"/updatePwd"})
    public XJson updatePwd(String oldPwd, String newPwd) {
        this.log.info("更新密码：" + oldPwd);
        UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user == null) {
            return XResp.pack(401, "更新失败， 登录过期", null);
        }
        Usr newUser = this.userService.findByAccount(user.getUsername());
        if (newUser == null) {
            return XResp.pack(401, "该用户不存在", "");
        }
        if (!this.passwordEncoder.matches(oldPwd, newUser.getPassword())) {
            this.log.info("旧密码比对失败");
            this.log.info(newUser.getPassword());
            return XResp.pack(401, "旧密码输入有误", "");
        } else if (this.userService.updatePwd(newUser.getId(), newPwd) == 0) {
            return XResp.pack(401, "密码修改失败", "");
        } else {
            return XResp.pack(200, "密码成功修改", "");
        }
    }

    @PostMapping({"updateShip"})
    public XJson updateShip(Usr u) {
        UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user == null) {
            return XResp.pack(401, "更新失败， 登录过期", null);
        }
        Usr newUser = this.userService.findByAccount(user.getUsername());
        if (newUser == null) {
            return XResp.pack(401, "该用户不存在", "");
        }
        u.setId(newUser.getId());
        this.userService.update(u);
        return XResp.pack(200, "更新成功...", null);
    }

    @PostMapping({"/updatePic"})
    public XJson updatePic(@RequestParam(value = "mypic", required = false) MultipartFile myfile) throws IOException {
        if (myfile == null && myfile.getSize() < 10) {
            return XResp.pack(401, "图片上传有误， 更新失败", "");
        }
        this.log.info("更新头像：" + myfile.getOriginalFilename());
        UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user == null) {
            return XResp.pack(401, "更新失败， 登录过期", null);
        }
        Usr newUser = this.userService.findByAccount(user.getUsername());
        if (newUser == null) {
            return XResp.pack(401, "该用户不存在", "");
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        this.largeFileService.add(uuid, myfile.getOriginalFilename(), myfile.getBytes());
        this.userService.updateImg(newUser.getId(), uuid);
        return XResp.pack(200, "更新图像成功", uuid);
    }
}
